Flask URL Construction: The url_for Function and Dynamic Routes
This article introduces the key methods for URL construction and handling in Flask, addressing the maintenance issues of hard-coded URLs. The core lies in the `url_for` function and dynamic routing. The `url_for` function dynamically generates URLs through view function names, avoiding hard-coding. Its basic usage is `url_for('view_function_name', parameter=value)`, such as generating the home page URL with `url_for('index')`. It supports parameter passing, e.g., `url_for('user_profile', user_id=100)` generates `/user/100`. By using `_external=True`, absolute URLs can be created, which are suitable for scenarios like emails or redirects. Dynamic routing allows route rules to include variable parameters, with the syntax `<converter:parameter_name>`. Converters include `int` (integer), `string` (string), and `path` (string with slashes), among others. The parameter name must match the view function parameter, and the type must be consistent; otherwise, a 404 error is returned. When combined, `url_for` is used in templates or views to generate links for dynamic routes. When route rules change, there is no need to modify the code, thus enhancing the maintainability of the project.
Read More